package org.jeecg.modules.demo.hd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.hd.entity.AppUser;
import org.jeecg.modules.demo.hd.mapper.AppUserMapper;
import org.jeecg.modules.demo.hd.service.IAppUserService;
import org.jeecg.modules.demo.hd.vo.user.authenticationVo;
import org.jeecg.modules.demo.hd.vo.user.registerUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;

/**
 * @Description: app_user
 * @Author: jeecg-boot
 * @Date: 2025-01-19
 * @Version: V1.0
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {


    @Override
    @Transactional
    public boolean addUser(registerUserVo vo) {
        AppUser user = new AppUser();
        BeanUtils.copyProperties(vo, user);
        //判断手机号码是否存在
        if (!checkPhone(vo.getPhone())) {
            user.setNick("多宝" + vo.getPhone().substring(vo.getPhone().length() - 4));
            user.setRegisterTime(new Date());
            baseMapper.insert(user);
            String gen = gen(user.getId());
            user.setGenCode(gen);
            baseMapper.updateById(user);
            //更新推荐人的邀请人数
            this.updateInviteNum(user.getInviteCode());
            return true;
        }
        //判断邀请码是否存在
        return false;
    }

    /**
     * 验证手机号是否存在，如果存在返回true，不存在返回false
     *
     * @param phone
     * @return
     */
    @Override
    public boolean checkPhone(String phone) {
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        AppUser appUser = this.baseMapper.selectOne(queryWrapper);
        return appUser != null;
    }

    @Override
    public boolean authentication(authenticationVo vo) {
        AppUser appUser = baseMapper.selectById(vo.getId());
        if (appUser != null) {
            BeanUtils.copyProperties(vo, appUser);
            //判断身份证号码是否存在
            QueryWrapper<AppUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("idcard", vo.getIdcard());
            int count = this.baseMapper.selectCount(queryWrapper).intValue();
            if (count > 0) {
                return false;
            }
            baseMapper.updateById(appUser);
            return true;
        }
        return false;
    }

    @Override
    public String getAuthentication(Long userId) {
        AppUser appUser = baseMapper.selectById(userId);
        if (appUser != null) {
            return appUser.getAuthenticationStatus();
        }
        return "-1";
    }


    /**
     * 通过邀请码更新 邀请的用户人数
     *
     * @param inviteCode
     * @return
     */
    private boolean updateInviteNum(String inviteCode) {
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gen_Code", inviteCode);
        AppUser appUser = this.baseMapper.selectOne(queryWrapper);
        if (appUser != null) {
            QueryWrapper<AppUser> countWrapper = new QueryWrapper<>();
            countWrapper.eq("invite_code", inviteCode);
            Integer aLong = baseMapper.selectCount(countWrapper).intValue();
            appUser.setInviteNum(aLong);
            baseMapper.updateById(appUser);
        }
        return true;
    }

    private final static int PRIME1 = 3;

    /**
     * 随机数据
     */
    private final static long SLAT = 123456L;

    /**
     * 邀请码长度
     */
    private final static int CODE_LENGTH = 6;

    private static final char[] CHARS = new char[]{'F', 'L', 'G', 'W', '5', 'X', 'C', '3', '9', 'Z', 'M', '6', '7', 'Y', 'R', 'T', '2', 'H', 'S', '8', 'D', 'V', 'E', 'J', '4', 'K', 'Q', 'P', 'U', 'A', 'N', 'B'};

    /**
     * PRIME2 与 CODE_LENGTH 互质，可保证（index * PRIME2）% CODE_LENGTH 在【0，CODE_LENGTH】上均匀分布
     */
    private final static int PRIME2 = 11;

    private String gen(Long id) {
        //补位，并扩大整体
        id = id * PRIME1 + SLAT;
        //将 id 转换成32进制的值
        long[] b = new long[CODE_LENGTH];
        //32进制数
        b[0] = id;
        for (int i = 0; i < CODE_LENGTH - 1; i++) {
            b[i + 1] = b[i] / CODE_LENGTH;
            //按位扩散
            b[i] = (b[i] + i * b[0]) % CODE_LENGTH;
        }
        b[5] = (b[0] + b[1] + b[2] + b[3] + b[4]) * PRIME1 % CODE_LENGTH;
        //进行混淆
        long[] codeIndexArray = new long[CODE_LENGTH];
        for (int i = 0; i < CODE_LENGTH; i++) {
            codeIndexArray[i] = b[i * PRIME2 % CODE_LENGTH];
        }
        StringBuilder buffer = new StringBuilder();
        Arrays.stream(codeIndexArray).boxed().map(Long::intValue).map(t -> CHARS[t]).forEach(buffer::append);
        return buffer.toString();
    }

}
